﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.IMSC.Model.ViewModels;
using TomNet.Utility.Data;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Account;

namespace TomNet.IMSC.Web.Areas.Runnings.Controllers
{
    public class RunningsController : BaseController
    {
        public INewHouseRunningsContract NewHouseRunningsContract { get; set; }
        public INewHouseRunningsStateContract NewHouseRunningsStateContract { get; set; }
        public IBuildingsContract BuildingsContract { get; set; }
        public IBuildingsBrokerageGroupContract BuildingsBrokerageGroupContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IStaffLoginContract StaffLoginContract { get; set; }
        public IImagesContract ImagesContract { get; set; }
        public IBrokerageRunningsContract BrokerageRunningsContract { get; set; }



        //State : 1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成
        //ReturnState : 1 默认 2 退房待审 3 已退房


        //列表===================================================================================

        [Description("新房流程-列表")]
        //[GlobalAuthorization]
        public ActionResult Index(int state = 1)
        {
            ViewData["state"] = state;
            return View();
        }

        [Description("新房流程-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IndexAsync(int pageIndex, int pageSize, int state, DateTime beginDate, DateTime endDate, int typeId = 0, string typevalue = "", int stateid = 0, int buildID = 0)
        {
            //获取权限
            //LoginModel loginModel = CookiesManagement.GetAutorModel();
            var cookies = CookiesManagement.GetCookies();
            var ticket = CookiesManagement.GetTicket(cookies);
            var loginModel = CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(loginModel);
            bool isAllAuthority = loginModel.AuthorityIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains("143");

            var query = from m in NewHouseRunningsContract.Entities.Where(x => true) select m;

            //查看 代理Id
            if (loginModel.AgentId > 0)
            {
                query = query.Where(m => m.AgentID.Equals(loginModel.AgentId));
            }

            //是否查看所有订单
            if (!isAllAuthority)
            {
                query = query.Where(m => m.OriginStaffID == loginModel.Id || m.SellStaffID == loginModel.Id);
            }

            //state : 1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成 9 退房待审 10 已退房 
            switch (state)
            {
                case 1://报备审批
                    query = query.Where(m => m.State.Equals(1) && m.ReturnState.Equals(1));
                    break;
                case 2://带看确认
                    query = query.Where(m => m.State.Equals(2) && m.ReturnState.Equals(1));
                    break;
                case 4://订金确认
                    query = query.Where(m => m.State.Equals(4) && m.ReturnState.Equals(1));
                    break;
                case 5://首付款确认
                    query = query.Where(m => m.State.Equals(5) && m.ReturnState.Equals(1));
                    break;
                case 6://成交确认
                    query = query.Where(m => m.State.Equals(6) && m.ReturnState.Equals(1));
                    break;
                case 3://失败完成
                case 10:
                    query = query.Where(m => m.State.Equals(3) || m.ReturnState.Equals(3));
                    break;
                case 7://成功完成
                case 8:
                    query = query.Where(m => (m.State.Equals(7) || m.State.Equals(8)) && m.ReturnState.Equals(1));
                    break;
                case 9://退房审核
                    query = query.Where(m => m.ReturnState.Equals(2));
                    break;
                default:
                    break;
            }

            //查询条件
            //SearchForm searchModel = JsonHelper.FromJson<SearchForm>(search);

            //时间
            beginDate = new DateTime(beginDate.Year, beginDate.Month, beginDate.Day, 0, 0, 0);
            endDate = new DateTime(endDate.AddDays(1).Year, endDate.AddDays(1).Month, endDate.AddDays(1).Day, 0, 0, 0);
            query = query.Where(m => m.FilingTime >= beginDate && m.FilingTime <= endDate);

            //楼盘
            if (buildID > 0)
            {
                query = query.Where(m => m.BuildingID.Equals(buildID));
            }

            //状态
            if (stateid > 0)
            {
                if (stateid.Equals(9))
                {
                    query = query.Where(m => m.ReturnState.Equals(2));
                }
                else if (stateid.Equals(10))
                {
                    query = query.Where(m => m.ReturnState.Equals(3));
                }
                else
                {
                    query = query.Where(m => m.State.Equals(stateid) && m.ReturnState.Equals(1));
                }
            }

            var list = (from m in query
                        select new NewHouseRunningsShow
                        {
                            Id = m.Id,
                            UserName = m.UserName,
                            UserPhone = m.UserPhone ,
                            CustomerName = m.CustomerName,
                            CustomerPhone = m.CustomerPhone + (m.State == 1 ? "(" + (NewHouseRunningsContract.Entities.Count(p => p.BuildingID == m.BuildingID && p.CustomerPhone==m.CustomerPhone && (new int[] { 1, 2, 4, 5, 6, 7, 8, 9 }).Contains(p.State))) + ")" : ""),
                            PropertyConsultantName = m.PropertyConsultantName,
                            StarTarget = m.StarTarget,
                            IntermediaryName = m.IntermediaryName,
                            SellStaff = (from m5 in StaffContract.Entities where m5.Id == m.SellStaffID select m5.Name).FirstOrDefault(),
                            FilingTime = m.FilingTime,
                            BandSawTime = m.BandSawTime,
                            SubscribeTime = m.SubscribeTime,
                            CustomerState = (from m1 in NewHouseRunningsStateContract.Entities where m1.Id == m.State select m1.Name).FirstOrDefault(),
                            BuildingName = m.BuildingName,
                            Area = m.Area,
                            Address = m.Address == null ? "" : m.Address,
                            BargainMoney = m.BargainMoney,
                            DownPaymentMoney = m.DownPaymentMoney,
                            TotalPrice = m.TotalPrice,
                            Brokerage = m.Brokerage == null ? "" : m.Brokerage,
                            Remark = m.Remark == null ? "" : m.Remark,
                            BuildingsBrokerageGroupID = m.BuildingsBrokerageGroupID,

                            //渠道人员
                            OriginStaff = (from m5 in StaffContract.Entities where m5.Id == m.OriginStaffID select m5.Name).FirstOrDefault(),

                            //带看单图片个数
                            BandSawPicCount = (from m2 in ImagesContract.Entities where m2.GroupID == 3 && m2.InterfixID == m.Id && m2.ImageType == 1 && m2.IsDeleted == false select m2).Count(),
                            //成交单图片个数
                            CompletePicCount = (from m3 in ImagesContract.Entities where m3.GroupID == 3 && m3.InterfixID == m.Id && m3.ImageType == 2 && m3.IsDeleted == false select m3).Count(),
                            //备案合同图片个数
                            RecordPicCount = (from m4 in ImagesContract.Entities where m4.GroupID == 3 && m4.InterfixID == m.Id && m4.ImageType == 3 && m4.IsDeleted == false select m4).Count()
                        });

            //类别
            if (typeId > 0 && !string.IsNullOrWhiteSpace(typevalue))
            {
                switch (typeId)
                {
                    case 1://客户姓名
                        list = list.Where(m => m.CustomerName.Contains(typevalue));
                        break;
                    case 2://客户电话
                        list = list.Where(m => m.CustomerPhone.Contains(typevalue));
                        break;
                    case 3://楼盘名称
                        list = list.Where(m => m.BuildingName.Contains(typevalue));
                        break;
                    case 4://经纪人姓名
                        list = list.Where(m => m.UserName.Contains(typevalue));
                        break;
                    case 5://门店名称
                        list = list.Where(m => m.IntermediaryName.Contains(typevalue));
                        break;
                    case 6://地推姓名
                        list = list.Where(m => m.OriginStaff.Contains(typevalue));
                        break;
                    case 7://业务姓名
                        list = list.Where(m => m.SellStaff.Contains(typevalue));
                        break;
                    case 8://流水号
                        list = list.Where(m => m.Id.ToString().Contains(typevalue));
                        break;
                    default:
                        break;
                }
            }
            else
            {
                list = list.Where(m => m.CustomerName.Contains(typevalue) || m.CustomerPhone.Contains(typevalue) || m.BuildingName.Contains(typevalue) || m.UserName.Contains(typevalue) || m.IntermediaryName.Contains(typevalue) || m.OriginStaff.Contains(typevalue) || m.SellStaff.Contains(typevalue) || m.Id.ToString().Contains(typevalue));
            }

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<NewHouseRunningsShow>().AsQueryable();// null;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = list.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
                
        //楼盘===================================================================================

        [Description("楼盘-列表")]
        //[GlobalAuthorization]
        public ActionResult BuildingsIndex()
        {
            //ViewData["layerindex"] = layerindex;
            return View();
        }

        [Description("楼盘-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult BuildingsIndexAsync(int pageIndex, int pageSize, string Name = "", string Address = "")
        {
            var query = from m in BuildingsContract.Entities.Where(x => !x.IsDeleted) select m;

            //条件搜索
            if (!string.IsNullOrWhiteSpace(Name))
            {
                query = query.Where(m => m.Name.Contains(Name));
            }
            if (!string.IsNullOrWhiteSpace(Address))
            {
                query = query.Where(m => m.Address.Contains(Address));
            }

            //var list = (from m in query
            //            select new UserShow
            //            {
            //                Id = m.Id,
            //                UserName = m.UserName,
            //                PassWord = m.PassWord,
            //                Phone = m.Phone,
            //                DepId = m.DepId,
            //                DepName = (from m1 in DepContract.Entities where m1.Id == m.DepId select m1.DepName).FirstOrDefault(),
            //                PositionName = (from m2 in PosContract.Entities where m2.Id == m.PositionId select m2.Name).FirstOrDefault(),// m.PositionId,
            //                Name = m.Name,
            //                Status = m.Status,
            //                No = m.No,
            //                IsLogin = m.IsLogin,
            //                Authority = m.Authority,
            //                IsLiability = m.IsLiability,
            //                CreatedTime = m.CreatedTime,
            //                IsDeleted = m.IsDeleted,
            //                IsLocked = m.IsLocked,
            //                AttSetName = (from n in AttSetContract.Entities where n.Id == m.AttSetId select n.Name).FirstOrDefault()
            //            });

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<Buildings>().AsQueryable();// null;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        //修改===================================================================================

        [Description("客户姓名-修改")]
        //[GlobalAuthorization]
        public ActionResult CustomerNameEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("客户姓名-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult CustomerNameEditAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { CustomerName = entity.CustomerName });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("客户电话-修改")]
        //[GlobalAuthorization]
        public ActionResult CustomerPhoneEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("客户电话-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult CustomerPhoneEditAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { CustomerPhone = entity.CustomerPhone });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("置业顾问-修改")]
        //[GlobalAuthorization]
        public ActionResult ConsultEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("置业顾问-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult ConsultEditAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { PropertyConsultantName = entity.PropertyConsultantName });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
                
        [Description("星标-设置")]
        public ActionResult SetStarTarget(int id)
        {

            if (id == 0) throw new Exception("参数错误");
            var entity = NewHouseRunningsContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            //星标默认值
            if (string.IsNullOrEmpty(entity.StarTarget))
            {
                entity.StarTarget = "0";
            }
            ViewBag.entity = entity;
            return View();
        }

        [Description("星标-设置")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditSetStarTarget(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                var count = NewHouseRunningsContract.UpdateDirect(d => entity.Id == d.Id, d => new NewHouseRunnings { StarTarget = entity.StarTarget, StarTargetRemark = entity.StarTargetRemark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }

        [Description("门牌号-修改")]
        //[GlobalAuthorization]
        public ActionResult AddressEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("门牌号-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult AddressEditAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { Address = entity.Address });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("备注-修改")]
        //[GlobalAuthorization]
        public ActionResult RemarkEdit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("备注-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult RemarkEditAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { Remark = entity.Remark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("操作员-查看")]
        //[GlobalAuthorization]
        public ActionResult OperList(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            //操作员
            ViewData["FilingAuditingStaff"] = StaffContract.Entities.Where(m => m.Id == entity.FilingAuditingStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["BandSawStaff"] = StaffContract.Entities.Where(m => m.Id == entity.BandSawStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["SubscribeStaff"] = StaffContract.Entities.Where(m => m.Id == entity.SubscribeStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["DownPaymentStaff"] = StaffContract.Entities.Where(m => m.Id == entity.DownPaymentStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["PutOnRecordStaff"] = StaffContract.Entities.Where(m => m.Id == entity.PutOnRecordStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["CompleteStaff"] = StaffContract.Entities.Where(m => m.Id == entity.CompleteStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["ReturnHouseStaff"] = StaffContract.Entities.Where(m => m.Id == entity.ReturnHouseStaffID).Select(m => m.Name).FirstOrDefault();
            ViewData["ReturnHouseAuditingStaff"] = StaffContract.Entities.Where(m => m.Id == entity.ReturnHouseAuditingStaffID).Select(m => m.Name).FirstOrDefault();

            ViewData["entity"] = entity;
            return View();
        }

        //操作===================================================================================

        [Description("取消订单")]
        [HttpPost, AjaxOnly]
        public ActionResult CancelAsync(int id)
        {
            var result = new AjaxResult();

            try
            {
                //获取登陆信息
                LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket(CookiesManagement.GetCookies()));
                //StaffLogin staffLogin = StaffLoginContract.Entities.Where(x => x.Id == login.Id).FirstOrDefault();

                //新房流程信息
                var newHouseRunningsModel = NewHouseRunningsContract.GetByKey(id);

                if (newHouseRunningsModel != null)
                {
                    int newState = newHouseRunningsModel.State;
                    switch (newHouseRunningsModel.State)
                    {
                        case 2:
                            newState = 1;//报备待审
                                         //修改状态，纪录操作员
                            NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(id), m => new NewHouseRunnings { State = newState });
                            break;
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                            newState = 2;//已取消
                                         //修改状态，纪录操作员
                            NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(id), m => new NewHouseRunnings { ReturnState = newState, ReturnHouseStaffID = login.Id, ReturnHouseTime = DateTime.Now });
                            break;
                        default:
                            break;
                    }

                    result.Type = AjaxResultType.Success;
                    result.Content = "取消成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "没有记录";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }

        [Description("房款操作")]
        //[GlobalAuthorization]
        public ActionResult PriceIndex(int id)
        {
            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            //佣金分组
            var query = BuildingsBrokerageGroupContract.Entities.Where(p => p.BuildingID.Equals(entity.BuildingID));
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (var item in query)
            {
                items.Add(new SelectListItem() { Text = item.Name + " | " + item.Brokerage, Value = item.Id.ToString() });
            }

            ViewBag.selectGroup = new SelectList(items, "Value", "Text");

            ViewData["entity"] = entity;
            return View();
        }

        [Description("房款操作")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult PriceIndexAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                var buildingsBrokerageGroupModel = BuildingsBrokerageGroupContract.GetByKey(entity.BuildingsBrokerageGroupID);

                var count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { BuildingsBrokerageGroupID = buildingsBrokerageGroupModel.Id, BuildingsBrokerageGroupName = buildingsBrokerageGroupModel.Name, Brokerage = buildingsBrokerageGroupModel.Brokerage, TotalPrice = entity.TotalPrice, Area = entity.Area, Address = entity.Address });

                BrokerageRunningsContract.InitBrokerage(1, entity.Id);//初始化佣金
                BrokerageRunningsContract.InitSalary(1, entity.Id);//初始化工资

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("操作")]
        //[GlobalAuthorization]
        public ActionResult OperIndex(int id, int state)
        {
            var entity = NewHouseRunningsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            ViewData["entity"] = entity;
            ViewData["state"] = state;
            return View();
        }

        [Description("操作")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult OperIndexAsync(NewHouseRunnings entity)
        {
            var result = new AjaxResult();
            try
            {
                //获取登陆信息
                LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket(CookiesManagement.GetCookies()));
                //StaffLogin staffLogin = StaffLoginContract.Entities.Where(x => x.StaffID == login.Id).FirstOrDefault();

                //新房流程信息
                var newHouseRunningsModel = NewHouseRunningsContract.GetByKey(entity.Id);

                int count = 0;
                int newState = newHouseRunningsModel.State;

                if (newHouseRunningsModel.ReturnState.Equals(1))
                {
                    if (newHouseRunningsModel.State.Equals(1))//报备待审
                    {
                        if (Request["OperType"].Equals("0"))//同意
                        {
                            newState = 2;
                        }
                        else//拒绝
                        {
                            newState = 3;
                        }

                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { State = newState, FilingAuditingStaffID = login.Id, FilingAuditingRemark = entity.FilingAuditingRemark, FilingAuditingTime = DateTime.Now });
                    }
                    else if (newHouseRunningsModel.State.Equals(4))//订金确认
                    {
                        newState = 5;
                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { State = newState, SubscribeStaffID = login.Id, BargainMoney = entity.BargainMoney, SubscribeTime = entity.SubscribeTime });
                    }
                    else if (newHouseRunningsModel.State.Equals(5))//首付款确认
                    {
                        newState = 6;
                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { State = newState, DownPaymentStaffID = login.Id, DownPaymentMoney = entity.DownPaymentMoney, DownPaymentTime = DateTime.Now });
                    }
                }
                else//退房
                {
                    if (newHouseRunningsModel.ReturnState.Equals(2))//退房审核
                    {
                        if (Request["OperType"].Equals("0"))//同意
                        {
                            newState = 3;
                        }
                        else//拒绝
                        {
                            newState = 1;
                        }
                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new NewHouseRunnings { ReturnState = newState, ReturnHouseAuditingStaffID = login.Id, ReturnHouseAuditingRemark = entity.ReturnHouseAuditingRemark, ReturnHouseAuditingTime = DateTime.Now });
                    }
                }


                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("操作")]
        [HttpPost, AjaxOnly]
        public ActionResult OperAsync(int id)
        {
            var result = new AjaxResult();

            try
            {
                //获取登陆信息
                LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket(CookiesManagement.GetCookies()));
                //StaffLogin staffLogin = StaffLoginContract.Entities.Where(x => x.Id == login.Id).FirstOrDefault();

                //新房流程信息
                var newHouseRunningsModel = NewHouseRunningsContract.GetByKey(id);

                if (newHouseRunningsModel != null)
                {
                    int count = 0;
                    int newState = newHouseRunningsModel.State;

                    if (newHouseRunningsModel.State.Equals(2))
                    {
                        newState = 4;//已带看
                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(id), m => new NewHouseRunnings { State = newState, BandSawStaffID = login.Id, BandSawTime = DateTime.Now });
                    }
                    else if (newHouseRunningsModel.State.Equals(6))
                    {
                        newState = 7;//已备案
                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(id), m => new NewHouseRunnings { State = newState, PutOnRecordStaffID = login.Id, PutOnRecordTime = DateTime.Now });
                    }
                    else if (newHouseRunningsModel.State.Equals(7))
                    {
                        newState = 8;//已完成
                        count = NewHouseRunningsContract.UpdateDirect(m => m.Id.Equals(id), m => new NewHouseRunnings { State = newState, CompleteStaffID = login.Id, CompleteTime = DateTime.Now });
                    }

                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "没有记录";
                }


            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }


    }
}